import React, { useState, useRef, useEffect } from 'react';
import { Button, message, Space } from 'antd';

import MicRecorder from 'mic-recorder-to-mp3';

const AudioRecorder: React.FC<{
  onRecordingComplete?: (blob: Blob) => void;
  disabled?: boolean;
}> = ({
  onRecordingComplete,
  disabled = false,
}) => {
  const [isRecording, setIsRecording] = useState(false);
  const [isBlocked, setIsBlocked] = useState(false);
  const recorderRef = useRef<any>(null); // 因为没类型，用 any

  useEffect(() => {
    // 初始化录音器
    recorderRef.current = new MicRecorder({ bitRate: 128 });

    // 检查权限
    navigator.mediaDevices
      ?.getUserMedia({ audio: true })
      .then(() => setIsBlocked(false))
      .catch(() => setIsBlocked(true));

    return () => {
      if (recorderRef.current) {
        // 组件卸载时停止录音（如果还在录）
        try {
          recorderRef.current.stop();
        } catch (e) {
          // ignore
        }
      }
    };
  }, []);

  const startRecording = async () => {
    if (disabled) {
      return;
    }
    if (isBlocked) {
      message.error('请允许麦克风访问权限');
      return;
    }
    try {
      await recorderRef.current.start();
      setIsRecording(true);
    } catch (err) {
      console.error('录音启动失败:', err);
      message.error('无法启动录音');
    }
  };

  const stopRecording = async () => {
    try {
      const [buffer, blob] = await recorderRef.current.stop().getMp3();
      setIsRecording(false);
      onRecordingComplete?.(blob);
      message.success('录音完成');
    } catch (err) {
      console.error('录音失败:', err);
      message.error('录音处理出错');
      setIsRecording(false);
    }
  };

  return (
    <Space>
      <Button
        onClick={startRecording}
        disabled={isRecording || disabled}
      >
        开始录音
      </Button>
      <Button
        onClick={stopRecording}
        disabled={!isRecording || disabled}
        danger
      >
        停止录音
      </Button>
      {isBlocked && <span style={{ color: 'red' }}>⚠️ 麦克风未授权</span>}
      {disabled && <span style={{ color: '#999' }}>录音已禁用</span>}
    </Space>
  );
};

export default AudioRecorder;
